#include "widget.h"
#include "ui_widget.h"
#include "card.h"
#include "log.h"
#include "bill.h"
#include "networkmanager.h"
#include <QTextCodec>
#include <QTimer>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonDocument>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    card = new Card;
    log = new Log;
    bill =new Bill;
    card->setWidget(this);
    log->setWidget(this);
    bill->setWidget(this);
    card->setLog(log);
    bill->setLog(log);
    log->setCard(card);
    bill->setCard(card);
    card->setBill(bill);
    log->setBill(bill);

    // 初始化 lcdNumber_carport（剩余停车位）的值为 8
    ui->lcdNumber_carport->display(8);

    networkManager = new NetworkManager(this);

    // 连接服务器：服务器地址是192.168.6.49 ，端口号是 8888
    // networkManager->connectToServer("192.168.6.49", 8888);
    networkManager->connectToServer("127.0.1.1", 8888);
    // 传递 networkManager 指针给 Card 和 Log 对象
    card->setNetworkManager(networkManager);
    log->setNetworkManager(networkManager);
    bill->setNetworkManager(networkManager);

    // 连接信号和槽
    connect(networkManager, &NetworkManager::dataReceived, this, &Widget::onDataReceived);
    connect(networkManager, &NetworkManager::dataReceived, card, &Card::onDataReceived);
    connect(networkManager, &NetworkManager::dataReceived, log, &Log::onDataReceived);
    connect(networkManager, &NetworkManager::dataReceived, bill, &Bill::onDataReceived);
}

Widget::~Widget()
{
    delete ui;
    delete card;
    delete log;
    delete bill;
    delete networkManager;
}

//跳转到会员界面
void Widget::on_pushButton_card_clicked()
{
    card->show();
    this->hide();
}

//跳转到日志界面
void Widget::on_pushButton_log_clicked()
{
    log->show();
    this->hide();
}
//跳转到账单界面
void Widget::on_pushButton_bill_clicked()
{
    bill->show();
    this->hide();
}
//发送入库车辆车牌
void Widget::on_pushButton_record_incar_clicked()
{
    // 获取各个编辑框中的文本信息
    QString car = ui->lineEdit_record_incar->text();

    // 按照指定格式组合信息数据
    QString dataString = QString("LICENSE_NUMBER|%1")
            .arg(car);

    // 计算详细数据的长度
    int len = dataString.toUtf8().size();

    QString lengthPrefix = QString("RECORD_INCAR|%1|").arg(len); // 构建包含长度信息的前缀

    QByteArray prefixToSend = lengthPrefix.toUtf8();// 将前缀转换为 QByteArray
    QByteArray dataToSend = dataString.toUtf8();// 将后面的内容转换为 QByteArray

    networkManager->sendData(prefixToSend);// 先发送长度前缀命令
    // 调试
    qDebug() << "Sent prefix:" << prefixToSend;
    networkManager->sendData(dataToSend); // 再发送后面的内容
    // 调试
    qDebug() << "Sent data:" << dataToSend;
}
//发送出库车辆车牌
void Widget::on_pushButton_record_outcar_clicked()
{
    // 获取各个编辑框中的文本信息
    QString car = ui->lineEdit_record_incar->text();

    // 按照指定格式组合信息数据
    QString dataString = QString("LICENSE_NUMBER|%1")
            .arg(car);

    // 计算详细数据的长度
    int len = dataString.toUtf8().size();

    QString lengthPrefix = QString("RECORD_INCAR|%1|").arg(len); // 构建包含长度信息的前缀

    QByteArray prefixToSend = lengthPrefix.toUtf8();// 将前缀转换为 QByteArray
    QByteArray dataToSend = dataString.toUtf8();// 将后面的内容转换为 QByteArray

    networkManager->sendData(prefixToSend);// 先发送长度前缀命令
    // 调试
    qDebug() << "Sent prefix:" << prefixToSend;
    networkManager->sendData(dataToSend); // 再发送后面的内容
    // 调试
    qDebug() << "Sent data:" << dataToSend;
}

//发送抬杆指令
void Widget::on_pushButton_lift_clicked()
{
    // 准备要发送的数据
    QByteArray dataToSend = "LIFT_BAR|lift|";
    // 调用 NetworkManager 的 sendData 方法发送数据
    networkManager->sendData(dataToSend);
    //调试
    qDebug() << "Sent1 data0: " << dataToSend;
}
//发送一直抬杆指令
void Widget::on_pushButton_keeplift_clicked()
{

    QByteArray dataToSend = "LIFT_BAR|keeplift|";
    networkManager->sendData(dataToSend);
    //调试
    qDebug() << "Sent1 data0: " << dataToSend;
}
//发送落杆指令
void Widget::on_pushButton_lower_clicked()
{
    QByteArray dataToSend = "LIFT_BAR|lower|";
    networkManager->sendData(dataToSend);
    //调试
    qDebug() << "Sent1 data0: " << dataToSend;
}
// 处理接收到的数据
void Widget::onDataReceived(const QByteArray &data)
{
    // 调试
    qDebug() << "Received data:" << data;

    //解析处理数据
    //使用 GBK 编码进行转换，因为”川“是GBK编码的，用UTF-8编码无法显示
    QTextCodec *codec = QTextCodec::codecForName("GBK");
    QString receivedData = codec->toUnicode(data);

    QStringList parts = receivedData.split('|'); // 按 '|' 分割字符串

    // 查找索引
    int in_licenseIndex = parts.indexOf("LICENSE_NUMBER_IN");
    int out_licenseIndex = parts.indexOf("LICENSE_NUMBER_OUT");
    int parking_numberIndex = parts.indexOf("AVAILABLE_PARKING_NUMBER");
    int parking_spacesIndex = parts.indexOf("AVAILABLE_PARKING_SPACES");
    int occupancyIndex = parts.indexOf("occupancy");
    int unoccupancyIndex = parts.indexOf("unoccupancy");
    int lift_barIndex =parts.indexOf("LIFT_BAR");

    // 检查是否找到对应索引且后面还有元素
    // 入库车牌号
    if (in_licenseIndex != -1 && in_licenseIndex + 1 < parts.size())
    {
        //响应，回传数据
        QByteArray dataToSend = data;
        networkManager->sendData(dataToSend);
        //调试
        qDebug() << "Sent1 data1:" << dataToSend;
        QString licenseNumber = parts.at(in_licenseIndex + 1);
        ui->lineEdit_license_in->setText(licenseNumber);
        // 设置定时器，只显示10s
        QTimer::singleShot(10000, [this]()
        {
            ui->lineEdit_license_in->clear();
        });
    }
    // 出库车牌号
    if (out_licenseIndex != -1 && out_licenseIndex + 1 < parts.size())
    {
        QString out_licenseNumber = parts.at(out_licenseIndex + 1);
        ui->lineEdit_license_out->setText(out_licenseNumber);
        QTimer::singleShot(10000, [this]()
        {
            ui->lineEdit_license_out->clear();
        });
    }
    // 剩余车位数
    if (parking_numberIndex != -1 && parking_numberIndex + 1 < parts.size())
    {
        QString parkingNumberStr = parts.at(parking_numberIndex + 1);
        bool ok;
        int parkingNumber = parkingNumberStr.toInt(&ok);
        if (ok)
        {
            ui->lcdNumber_carport->display(parkingNumber);
        }
    }
    // 车位状态图
    if (parking_spacesIndex != -1 && parking_spacesIndex + 1 < parts.size())
    {
        QString parkingSpaces = parts.at(parking_spacesIndex + 1);
        QString color;
        if (occupancyIndex != -1)
        {
            color = "rgb(69, 184, 255)";
        }
        else if (unoccupancyIndex != -1)
        {
            color = "rgb(193, 193, 193)";
        }

        if (!color.isEmpty())
        {
            for (int i = 1; i <= 8; ++i)
            {
                QString currentSpace = QString("A%1").arg(i);
                if (parkingSpaces == currentSpace)
                {
                    QString labelName = QString("label_A%1").arg(i);
                    QLabel* label = this->findChild<QLabel*>(labelName);
                    if (label)
                    {
                        QString styleSheet = QString("background-color: %1;").arg(color);
                        label->setStyleSheet(styleSheet);
                    }
                }
            }
        }
    }
    //处理抬杆结果
    if (lift_barIndex != -1 && lift_barIndex + 1 < parts.size()&& this->isVisible())
    {
        QString result = parts.at(lift_barIndex + 1).trimmed();
        if (result == "lift")
        {
            QMessageBox::information(nullptr, "提示", "已抬杆");
        }
    }
    //处理一直抬杆结果
    if (lift_barIndex != -1 && lift_barIndex + 1 < parts.size()&& this->isVisible())
    {
        QString result = parts.at(lift_barIndex + 1).trimmed();
        if (result == "keeplift")
        {
            QMessageBox::information(nullptr, "提示", "已抬杆");
        }
    }
    //处理抬杆结果
    if (lift_barIndex != -1 && lift_barIndex + 1 < parts.size()&& this->isVisible())
    {
        QString result = parts.at(lift_barIndex + 1).trimmed();
        if (result == "lower")
        {
            QMessageBox::information(nullptr, "提示", "已落杆");
        }
    }
}






